package com.example.demo.config;

import com.example.demo.exception.BusinessException;
import com.example.demo.utils.HttpCode;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;

public class DoubleSerializer extends JsonSerializer<Double> {
    @Override
    public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
            throws IOException {
        if(Double.isNaN(value)){
            throw new BusinessException(HttpCode.INTERNAL_SERVER_ERROR, "value is NaN");
        }
        BigDecimal d = new BigDecimal(value.toString());
        gen.writeNumber(d.stripTrailingZeros().toPlainString());
    }

    @Override
    public Class<Double> handledType() {
        return Double.class;
    }
}
